<template>
  <div>
    <el-upload
      :file-list="fileList"
      class="upload-demo"
      :action="action"
      :multiple="multiple"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      :limit="limit"
      :headers="headers"
      :on-exceed="handleExceed"
      :on-success="handleSuccess"
    >
      <el-button type="primary">点击上传</el-button>
      <!-- <el-icon><Plus /></el-icon> -->
    </el-upload>
    <!-- <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog> -->
  </div>
</template>

<script setup lang="ts">
import type { UploadProps, UploadUserFile } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
const props = defineProps({
  prop: {
    type: String,
    required: true,
  },
  action: {
    type: String,
    required: true,
  },
  multiple: {
    type: Boolean,
    required: true,
  },
  limit: {
    type: Number,
    required: true,
  },
  headers: {
    type: Object,
    required: true,
  },
  fileLists: {
    type: String
  },
});
const emit = defineEmits(["uploadFiles"]);
let fileList = ref<UploadUserFile[]>([]);
let imgLists = ref<string[]>([]);
// const dialogImageUrl = ref('')
// const dialogVisible = ref(false)
watch(() => props.fileLists,() => {
  if (props.fileLists) {
    fileList.value = []
    let list = props.fileLists.split(",");
    imgLists.value = list
    list.forEach((item) => {
      let fileName =
        item.split("upload/")[1]
      fileList.value.push({
        name: fileName,
        url: item,
      });
    });
  }
})
onMounted(() => {
  if (props.fileLists) {
    fileList.value = []
    let list = props.fileLists.split(",");
    imgLists.value = list
    list.forEach((item) => {
      let fileName =
        item.split("upload/")[1]
      fileList.value.push({
        name: fileName,
        url: item,
      });
    });
  }
})
const handleRemove: UploadProps["onRemove"] = (file:any, uploadFiles) => {
  imgLists.value = imgLists.value.filter((item:any) => 
     item != file.url
  );
  emit("uploadFiles", props.prop, imgLists.value.toString());
};
const handlePreview: UploadProps["onPreview"] = (uploadFile) => {
  // dialogImageUrl.value = uploadFile.url!
  // dialogVisible.value = true
};
const handleExceed: UploadProps["onExceed"] = (files, uploadFiles) => {
  ElMessage.warning(`只能上传${props.limit}个文件`);
};
const beforeRemove: UploadProps["beforeRemove"] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(`确定要删除 ${uploadFile.name} 吗?`).then(
    () => true,
    () => false
  );
};
const handleSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
  imgLists.value.push(process.env.VUE_IMG_BASE_URL + 'upload/' +  response.data.newFilename);
  emit("uploadFiles", props.prop, imgLists.value.toString());
};
</script>

<style scoped></style>
